<?php

class SiteController extends Controller
{
    ///帮助信息提示
    const helpmsg = "感谢您关注【沈阳远大科技创业园有限公司】\n微信号：sci_park\n
    介绍创新科技，传播正能量，期待您的参与，您的关注！\n
    目前平台功能如下：\n
    \n
    请输入****####，工资卡后4位和身份证后4位(eg.12347890)查询工资卡后4位为1234和身份证后4位为7890最新的工资条。\n
    请输入****####YYMM，工资卡后4位和身份证后4位，年2位月2位(eg.123478901501)查询查询工资卡后4位为1234和身份证后4位为7890，2015年1月份的工资条。\n
    ";
    
    
    const token= 'tokenaccesskey'; //填写你设定的key
    const appid ='wx1ef74b5716b9bcf4';
    const appsecret = 'cbfda9bd25e1841ad159eaf482e216fb';
    
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
    	// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
        /*
        echo('echo index');
        print('print index');
        
	    if (Yii::app()->user->isGuest) 
		{
			//$this->actionLogin();
            //actionMain();
		}
		else 
		{
			//$this->actionMain();
		}
        */
        $this->render('index');
	}
    private function receiveEvent($object)
    {
        //$contentStr = "";
        $event = $object->getRevEvent();
        switch ($event['event'])
        {
            case "subscribe":  //"subscribe"<strong></strong>
                //$contentStr[] = array("Title" =>"欢迎关注远大科技园", "Description" =>"点击图片关注或者搜索号码beancube", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/11.jpg", "Url" =>"weixin://addfriend/beancube");
                 $contentStr = self::helpmsg;
                 //"【2】 查公交，如输入：苏州公交178"."\n".
                 //"【3】 翻译，如输入：翻译I love you"."\n".
                 //"【4】 苏州信息查询，如输入：苏州观前街"."\n".
                 //"更多内容，敬请期待...";
                 break;
            case "unsubscribe":
                $contentStr = "886";
                break;
            case "CLICK":
                switch ($event['key'])
                {
                    case "MK11":
                        $contentStr[] = array("Title" =>"远大科技园", "Description" =>"远大科技园简介", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/11.jpg", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzA3OTI4OTcxMw==&mid=200039412&idx=1&sn=79c6ab083c199e6d7d0568aeb9fd8852#rd");
                        break;
                    case "MK12":
                        $contentStr[] = array("Title" =>"远大科技园创新模式", "Description" =>"远大科技园创新模式", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/12.png", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzA3OTI4OTcxMw==&mid=200039419&idx=1&sn=6c24c05edb358832b6bfd14df54f84e9#rd");
                        break;
                    case "MK13":
                        $contentStr[] = array("Title" =>"七位一体的创新功能体系", "Description" =>"七位一体的创新功能体系", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/13.jpg", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzA3OTI4OTcxMw==&mid=200039456&idx=1&sn=4505e4ecd459771f13a5823ae144b3ba#rd");
                        break;
                    case "MK14":
                        $contentStr[] = array("Title" =>"联系我们", "Description" =>"联系我们", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/14.bmp", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzA3OTI4OTcxMw==&mid=200039475&idx=1&sn=571331ed0404fc954447c22807ac1b75#rd");
                        break;
                    case "MK15":
                        $contentStr[] = array("Title" =>"公司简介15", "Description" =>"方倍工作室提供移动互联网相关的产品及服务，包括新浪微博应用、微信公众平台接口、手机版网站等", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/15.jpg", "Url" =>"weixin://addfriend/beancube");
                        break;
                    case "MK21":
                        $contentStr[] = array("Title" =>"信息服务平台", "Description" =>"远大科技创业园以现代网络信息技术为手段，完善不同类别的情报数据库资源，通过开展对世界多区域，多领域的情报搜集、辨别、筛选、提炼、加工、转化等工作，更好的服务于远大集团现有产业项目以及进驻科技园的孵化企业。", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/21.jpg", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzA3OTI4OTcxMw==&mid=200047479&idx=1&sn=435ee5db804c6689a6900d32ebf6273b#rd");
                        break;
                    case "MK22":
                        $contentStr[] = array("Title" =>"人才服务平台", "Description" =>"“国以才立，政以才治，业以才兴”，我们以树立人才资源是第一资源的观念，营造有利于人才发展的良好环境，把“吸引国际化高端科研人才回流沈阳”放在战略的、全局的高度来认识，为其消除后顾之忧，促其安心创业，扎根沈阳。", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/22.jpg", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzA3OTI4OTcxMw==&mid=200047493&idx=1&sn=46688574ea42d8fedf3ac5e387eb41b0#rd");
                        break;
                    case "MK23":
                        $contentStr[] = array("Title" =>"融资服务平台", "Description" =>"为打造具有强大创新动力与雄厚创新实力的科技型园区, 科技园为中小型入孵企业提供融资服务，借助远大企业集团的雄厚财力与企业信誉，通过与金融机构构建的长期合作机制，解决中小企业创业资金不足，融资能力弱等问题，消除了入孵企业的后顾之忧。", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/23.jpg", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzA3OTI4OTcxMw==&mid=200047511&idx=1&sn=2035a67bf867f1b9020f52f6d4254d85#rd");
                        break;
                    case "MK24":
                        $contentStr[] = array("Title" =>"成果交易平台", "Description" =>"科技园为中小型入孵企业提供融资服务，借助远大企业集团的雄厚财力与企业信誉，通过与金融机构构建的长期合作机制，解决中小企业创业资金不足，融资能力弱等问题，消除了入孵企业的后顾之忧。", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/24.jpg", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzA3OTI4OTcxMw==&mid=200047525&idx=1&sn=738ece568c95277e6fc7d0bd173e364b#rd");
                        break;
                    case "MK25":
                        $contentStr[] = array("Title" =>"创业服务平台", "Description" =>"科技园为创业期中小企业提供空间载体、专业孵化服务、管理咨询、市场拓展、关系网建设等。强化内生式发展理念，增强产业创新活力，成为创业人才的“理想栖息地”。", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/25.jpg", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzA3OTI4OTcxMw==&mid=200047504&idx=1&sn=a2203d10476cae83fb0f391f67051ce2#rd");
                        break;
                    case "MK31":
                        $contentStr[] = array("Title" =>"公司简介31", "Description" =>"您正在使用的是远大科技园微信服务", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/11.jpg", "Url" =>"weixin://addfriend/beancube");
                        break;
                    case "MK32":
                        $contentStr[] = array("Title" =>"公司简介32", "Description" =>"您正在使用的是远大科技园微信服务", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/11.jpg", "Url" =>"weixin://addfriend/beancube");
                        break;
                    case "MK33":
                        //$contentStr[] = array("Title" =>"公司简介33", "Description" =>"方倍工作室提供移动互联网相关的产品及服务，包括新浪微博应用、微信公众平台接口、手机版网站等", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/11.jpg", "Url" =>"weixin://addfriend/beancube");
                        $contentStr = '为使远大科技园营造公平、公正的工作晋升环境，确保“下情上达”的顺畅沟通渠道。同时，为实现远大科技园的“筑巢引凤，广纳贤才”计划，我们建立了“高管直通车，对话决策者”专用邮箱info@cnyd-sci.com倾听你的声音，留下你的足印！';
                        break;
                    default:
                        $contentStr[] = array("Title" =>"默认菜单回复", "Description" =>"您正在使用的是远大科技园微信服务", "PicUrl" =>"http://comm.oschina.mopaas.com/communityhelp/img/11.jpg", "Url" =>"weixin://addfriend/beancube");
                        break;
                }
                break;
            default:
                $contentStr = "receive a new event: ".$object->Event;
                break;      

       }
        return $contentStr;
    }
    private function getwish ($rid) {
        $criteria=new CDbCriteria;  
        $criteria->condition ='ID=:ID';
        $criteria->params=array(':ID'=>$rid,);
        $criteria->order = 'id desc';
        $criteria->limit = 1;
        //$gz = Gz::model()->findByAttributes(,null,array('order'=>'id desc'));
        $gz = Command::model()->find($criteria);
         if($gz===null)
            $strgz = '';
        else {
            $strgz =$gz->context;
        }
        $strgz = iconv("UTF-8","GBK//IGNORE",$strgz);
        return $strgz;
    }
    public function actionWish() {
        $ik =  rand(1,100);
        echo 'wish : ' . $this->getwish($ik);
    } 
    private function getghcode ($openid) {
        $criteria=new CDbCriteria;  
        $criteria->condition ='openid=:openid';
        $criteria->params=array(':openid'=>$openid,);
        $criteria->order = 'id desc';
        $criteria->limit = 1;
        //$gz = Gz::model()->findByAttributes(,null,array('order'=>'id desc'));
        $gz = Ghinfo::model()->find($criteria);
         if($gz===null)
            $strgz = '';
        else {
            $strgz =$gz->ghcode;
        }
        return $strgz;
    }
    //计算定义方式 帐号后四位,身份证4
   private function clauGz($openid ,$yearmonth) {
        //$showarr = array('tmps2','name','bzgz','tmps4','glbt','tmps5','yfugz','cb','db','tf','nb','yfagz','yalbx','sybx','yilbx','gjj','gs','tmps6','hdjf','sfgz');
        $showarr = array('tmps2','name','bzgz','mqdays','cqdays','jbgz','tmps4','glbt','tmps7','tmps8','tmps5','yfagz','cb','db','tf','nb','yfagz','yalbx','sybx','yilbx','gjj','gs','tmps6','hdjf','sfgz');
        //确定字符串长度 是8 = 4+4  还是 12 = 4+ 4 + 4
        $criteria=new CDbCriteria; 
        $strlen = strlen($yearmonth);
        if ($strlen==8){
            $YHcard = substr($yearmonth, 0, 4);
            $IDcard = substr($yearmonth, 4, 4);
            $criteria->condition ='tmpi1=:yhcard and tmpi2=:idcard';
            $criteria->params=array(':yhcard'=>$YHcard,':idcard'=>$IDcard);
        } elseif ($strlen==12) {
            $YHcard = substr($yearmonth, 0, 4);
            $IDcard = substr($yearmonth, 4, 4);
            $year = '20'.substr($yearmonth, 8, 2);
            $month = substr($yearmonth, 10, 2);
            $criteria->condition ='tmpi1=:yhcard and tmpi2=:idcard and year=:year and month=:month';
            $criteria->params=array(':yhcard'=>$YHcard,':idcard'=>$IDcard,':year'=>$year,':month'=>$month);
        } else {
            return '未检索到工资记录！请确认工资后4位和身份证后4位。';
        }

        $criteria->order = 'id desc';
        $criteria->limit = 1;
        //$gz = Gz::model()->findByAttributes(,null,array('order'=>'id desc'));
        $gz = Gz::model()->find($criteria);
        
        //$gz = Gz::model()->findByAttributes(array('tmps3'=>$openid,'year'=>$year,'month'=>$month));
        if($gz===null)
            $strgz = '';
        else {
            $strgz = '';
            foreach($showarr as $key){
                $label = $gz->getAttributeLabel($key);
                $value = $gz->{$key};
                $strgz .= "$label : $value\n";
            }
        }
        //return ($strgz=='') ? '未检索到'.$year.'.'.$month.'工资记录！' : $strgz;
        return ($strgz=='') ? '未检索到工资记录！请确认工资后4位和身份证后4位。' : $strgz;
    }
 
    public function actionWeixin() { 
        //$fh = fopen('php://stdout', 'w');
        //fwrite($fh, "1start weixin");
        
        //$this->actionMenu();
        /**
 * $options = array(
 *         	'token'=>'tokenaccesskey', //填写你设定的key
 *             'appid'=>'wx563bfa2823a52121',
 *             'appsecret'=>'d241689734e6656da22c4c91a1f66b30'
 *         );
 */
         $options = array(
        	'token'=>self::token, //填写你设定的key
            'appid'=>self::appid,
            'appsecret'=>self::appsecret
        );
        // fwrite($fh, "2start weixin " .  implode(",", $options)); 
     	 $weObj = new Wechat($options);
        // fwrite($fh, "weixin init"); 
        //$weObj->valid();
        //获取菜单操作:
        //$menu = $weObj->getMenu();
        //设置菜单
        /*
        $menu1 = array(array('type'=>'click','name'=>'园区介绍','key'=>'MK11'),
               array('type'=>'click','name'=>'定位','key'=>'MK12'),
               array('type'=>'click','name'=>'功能','key'=>'MK13'),
               array('type'=>'click','name'=>'联系我们','key'=>'MK14'),
               array('type'=>'view','name'=>'招聘人才','url'=>'http://search.51job.com/list/%2B,%2B,%2B,%2B,%2B,%2B,%25C9%25F2%25D1%25F4%25D4%25B6%25B4%25F3%25BF%25C6%25BC%25BC%25B4%25B4%25D2%25B5%25D4%25B0%25D3%25D0%25CF%25DE%25B9%25AB%25CB%25BE,2,%2B.html?lang=c&stype=1&image_x=36&image_y=17'),   );
        
        $menu2 = array(array('type'=>'click','name'=>'信息服务平台','key'=>'MK21'),
               array('type'=>'click','name'=>'人才服务平台','key'=>'MK22'),
               array('type'=>'click','name'=>'融资服务平台','key'=>'MK23'),
               array('type'=>'click','name'=>'成果交易平台','key'=>'MK24'),
               array('type'=>'click','name'=>'创业服务平台','key'=>'MK25'),   );
        
        $menu3 = array(array('type'=>'view','name'=>'SCI社区','url'=>'http://wsq.qq.com/reflow/174090637'),
                       array('type'=>'view','name'=>'SCI活动','url'=>'http://www.17f8.me/mobile/index.jsp?banner=/image/yiqifaba/top2.jpg&copyRight=5ZKM5bmz6bi95a2Q&platform=1&wuid=7253'),
                       array('type'=>'click','name'=>'SCI申述邮箱','url'=>'MK33'),
               );
               
        $newmenu =  array(
            "button"=>
            array(
                //array('type'=>'click','name'=>'最新消息','key'=>'MK'),
                //array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
                array('name'=>'科 技 园','sub_button'=>$menu1),
                array('name'=>'孵化服务','sub_button'=>$menu2),
                array('name'=>'微 社 区','sub_button'=>$menu3),
            )
        );
        //fwrite($fh,  'create menu');
        $result = $weObj->createMenu($newmenu);
        //fwrite($fh,  $result);
        //fclose($fh);
        */
        //fwrite($fh,  file_get_contents("php://input"));
        $rev = $weObj->getRev();
        //$fh = fopen('php://stdout', 'w');
        //fwrite($fh, "rec" .  implode(",", $rev)); 
         $type = $rev->getRevType();
         //fwrite($fh, "rec" .  $type); 
         switch($type) {
        		case Wechat::MSGTYPE_TEXT:
                    //fwrite($fh, "\nstart gz calu " .$rev->getRevFrom() . ' '.$rev->getRevContent());
                    //如果是管理员的 可以群发消息 和 数据库管理操作，例如 增加一条好的祝福信息 和 新命令行
                    
                    
                    if ($rev->getRevFrom()=='') 
                    {
                        
                    } else {
                        
                    }
                    $revcontent = $rev->getRevContent();
                    switch($revcontent){
                        case 'help':
                            $textinfo = self::helpmsg;
                            break;
                         case '?':
                            $textinfo = self::helpmsg;
                            break;
                         case '？':
                            $textinfo = self::helpmsg;
                            break;
                        case 'love':
                            $count= Command::model()->count('', null);
                            $ik =  rand(1,$count);
                            $textinfo =  $this->getwish($ik);
                            break;
                        default:
                            $command = substr($revcontent , 0 , 2);
                            //fwrite($fh, "\ncommand:$command");
                            if ($command=='gh'){
                                //工号绑定功能 --取消 邦定方式
                                /*
                                $ghcode = substr($revcontent , 2);
                                $gh = $this->getghcode($rev->getRevFrom());
                                if ($gh=='') {
                                    $ghinfo =  new Ghinfo;
                                    $ghinfo->ToUserName = $rev->getRevTo();
                                    $ghinfo->ghcode = $ghcode;
                                    $ghinfo->openid = $rev->getRevFrom();
                                    if ($ghinfo->save())
                                        $textinfo = "工号[$ghcode]注册成功！请输入YYYYMM(eg.201501)查询2015年一月的工资条！";
                                    else 
                                        $textinfo = "工号[$ghcode]注册失败！请重试或与系统管理员联系！！";
                                } else {
                                    $textinfo = "工号[$gh]已经被注册了，请与系统管理员联系！";
                                }
                                */
                               
                            }                            
                            else 
                                $textinfo = $this->clauGz($rev->getRevFrom(),$rev->getRevContent());
        			        //$weObj->text($gz)->reply();    
                    }
                    $weObj->text($textinfo)->reply();
        			break;
        		case Wechat::MSGTYPE_EVENT:
        			$eventrec =  $this->receiveEvent($rev);
                    //fwrite($fh, 'isarray : '.is_array($eventrec) ? 'array' :'not array');
                    if (is_array($eventrec))
                        $weObj->news($eventrec)->reply(); 
                    else 
                        $weObj->text($eventrec)->reply();
        			break;
        		case Wechat::MSGTYPE_IMAGE:
    
        			break;
        		default:
        			$weObj->text("help info")->reply();
        }
        //fclose($fh);
    }
    
    public function actionGetusers() {
        //$fh = fopen('php://stdout', 'w');
        $options = array(
        	'token'=>self::token, //填写你设定的key
            'appid'=>self::appid,
            'appsecret'=>self::appsecret
        );
     	$weObj = new Wechat($options);
        $rev  =  $weObj->get_user_list();
        $openids = $rev['data']['openid'];
        foreach($openids as $openid){
            //echo($openid.'='.$this->actionGetuserinfo($openid) . '<BR />');
            $ghinfo = new Ghinfo;
            $ghinfo->openid = $openid;
            $ghinfo->tmps3 =     $this->actionGetuserinfo($openid);
            $ghinfo->save();
        }
        
        //fwrite($fh, "\nactionGetusers" .$weObj->errCode . ' | ' . $weObj->errMsg); 
        //fwrite($fh, "\nactionGetusers" .implode(',',$rev));
        //fclose($fh);
    }
    
    public function actionGetuserinfo($openid) {
        $options = array(
        	'token'=>self::token, //填写你设定的key
            'appid'=>self::appid,
            'appsecret'=>self::appsecret
        );
     	$weObj = new Wechat($options);
        $rev  =  $weObj->get_user_info($openid);
        //var_dump($rev);
        return  $rev['nickname'];
    }
    
    public function actionSendmsg(){
        //$fh = fopen('php://stdout', 'w');
        $options = array(
        	'token'=>self::token, //填写你设定的key
            'appid'=>self::appid,
            'appsecret'=>self::appsecret
        );
     	$weObj = new Wechat($options);
        //$weObj->valid();
        $context = "群发消息：".self::helpmsg;
        
        //fwrite($fh, "sendmsg" . $context); 
        $rev  =  $weObj->sendMsg($context);
        
        
        //fwrite($fh, "sendmsg" .$weObj->errCode . ' | ' . $weObj->errMsg); 
        //fclose($fh);
    }

    public function actionNewgz($msg){
        //$fh = fopen('php://stdout', 'w');
        $options = array(
        	'token'=>self::token, //填写你设定的key
            'appid'=>self::appid,
            'appsecret'=>self::appsecret
        );
     	$weObj = new Wechat($options);
        //$weObj->valid();
        $context = $msg;
        
        //fwrite($fh, "sendmsg" . $context); 
        $rev  =  $weObj->sendMsg($context);
        
        
        //fwrite($fh, "sendmsg" .$weObj->errCode . ' | ' . $weObj->errMsg); 
        //fclose($fh);
    }
    public function actionMenu() {
        $fh = fopen('php://stdout', 'w');
       $options = array(
        	'token'=>self::token, //填写你设定的key
            'appid'=>self::appid,
            'appsecret'=>self::appsecret
        );
            /* */
     	$weObj = new Wechat($options);
        //$weObj->valid();
        //获取菜单操作:
        //$menu = $weObj->getMenu();
        //设置菜单
        $menu1 = array(array('type'=>'click','name'=>'园区介绍','key'=>'MK11'),
               array('type'=>'click','name'=>'定位','key'=>'MK12'),
               array('type'=>'click','name'=>'功能','key'=>'MK13'),
               array('type'=>'click','name'=>'联系我们','key'=>'MK14'),
               array('type'=>'view','name'=>'招聘人才','url'=>'http://search.51job.com/'),   );
        
        $menu2 = array(array('type'=>'click','name'=>'信息服务平台','key'=>'MK21'),
               array('type'=>'click','name'=>'人才服务平台','key'=>'MK22'),
               array('type'=>'click','name'=>'融资服务平台','key'=>'MK23'),
               array('type'=>'click','name'=>'成果交易平台','key'=>'MK24'),
               array('type'=>'click','name'=>'创业服务平台','key'=>'MK25'),   );
        
        $menu3 = array(array('type'=>'view','name'=>'SCI社区','url'=>'http://wsq.qq.com/reflow/174090637'),
                       array('type'=>'view','name'=>'SCI活动','url'=>'http://www.17f8.me/mobile/index.jsp?banner=/image/yiqifaba/top2.jpg&copyRight=5ZKM5bmz6bi95a2Q&platform=1&wuid=7253'),
                       array('type'=>'click','name'=>'SCI申述邮箱','key'=>'MK33'),
               );
               
        $newmenu =  array(
            "button"=>
            array(
            //array('type'=>'click','name'=>'最新消息','key'=>'MK'),
            //array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
            array('name'=>'科 技 园','sub_button'=>$menu1),
            array('name'=>'孵化服务','sub_button'=>$menu2),
            array('name'=>'微 社 区','sub_button'=>$menu3),
            )
        );
        $result = $weObj->createMenu($newmenu);
        
        fwrite($fh, "\nmenu" .$weObj->errCode . ' | ' . $weObj->errMsg); 
        fclose($fh);
    }

    public function actionMain(){
        $this->renderPartial('main');//,array('form'=>$form));
    }
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-Type: text/plain; charset=UTF-8";

				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
    
    /**
    * 管理框架页 left
    */
    public function actionLeft()
    {
        if(Yii::app()->user->isGuest){
            $this->redirect(array('site/login'));
        }
        else{
            Yii::app()->getClientScript()->registerCoreScript('jquery');
            //$this->layout='left';
            //$this->render('left');
            $this->renderPartial('left');
            //$this->redirect(Yii::app()->request->baseUrl.'/left.php');
        }
    }
 
     /**
    * 管理框架页 tree
    */
    public function actionTree()
    {
        if(Yii::app()->user->isGuest){
            $this->redirect(array('site/login'));
        }
        else{
            Yii::app()->getClientScript()->registerCoreScript('jquery');
            //$this->layout='left';
            //$this->render('left');
            $this->renderPartial('tree');
            //$this->redirect(Yii::app()->request->baseUrl.'/left.php');
        }
    }
    
        /**
    * 管理框架页 top
    */
    public function actionTop()
    {
        if(Yii::app()->user->isGuest){
            $this->redirect(array('site/login'));
        }
        else{
            Yii::app()->getClientScript()->registerCoreScript('jquery');
            //$this->layout='left';
            //$this->render('left');
            $this->renderPartial('top');
            //$this->redirect(Yii::app()->request->baseUrl.'/left.php');
        }
    }
    /**
    * 管理框架页 default
    */
    public function actionDefault()
    {
        if(Yii::app()->user->isGuest){
            $this->redirect(array('site/login'));
        }
        else{
            Yii::app()->getClientScript()->registerCoreScript('jquery');
            //$this->layout='left';
            //$this->render('left');
            $this->renderPartial('default');
            //$this->redirect(Yii::app()->request->baseUrl.'/left.php');
        }
    }
    
    /**
     * Fills the JS tree on an AJAX request.
     * Should receive parent node ID in $_GET['root'],
     *  with 'source' when there is no parent.
     */
    public function actionAjaxFillTree()
    {
        // accept only AJAX request (comment this when debugging)
        if (!Yii::app()->request->isAjaxRequest) {
            exit();
        }
        // parse the user input
        $parentId = "NULL";
        if (isset($_GET['root']) && $_GET['root'] !== 'source') {
            $parentId = (int) $_GET['root'];
        }
        // read the data (this could be in a model)
        $children = Yii::app()->db->createCommand(
            "SELECT m1.id, m1.streetname AS text, m2.id IS NOT NULL AS hasChildren "
            . "FROM {{street}} AS m1 LEFT JOIN {{sq}} AS m2 ON m1.id=m2.streetid "
            //. "WHERE m1.id <=> $parentId "
            . "GROUP BY m1.id ORDER BY m1.name ASC"
        )->queryAll();
        echo str_replace(
            '"hasChildren":"0"',
            '"hasChildren":false',
            CTreeView::saveDataAsJson($children)
        );
    }
}